package com.iweb.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

public class RestParser {

    /**
     * 用于restFul解析PUT和DELETE请求id
     *
     * @param request
     * @param pattern
     * @return
     */
    public static Integer id(HttpServletRequest request, String pattern) {
        String url = request.getRequestURI().replaceAll("/", "").replace(pattern, "");
        return Convert.toInt(url);
    }

    /**
     * 获取json参数
     * @param req
     * @return
     */
    public static JSONObject arg2json(HttpServletRequest req) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = req.getReader();
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSONUtil.parseObj(sb.toString());
    }

}
